<script setup lang="ts">
import {ref} from "vue";
import mainIcon from '../../assets/images/logo.svg';
import {ElNotification, FormInstance, FormRules} from "element-plus";
import axios from "axios";
import {ServerHost, loginUser} from "@/main";

const accountDialogVisible = ref(false)
const accountTabActiveName = ref('loginByUsername')

const validateNotNull = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error('请输入'))
  } else {
    callback()
  }
}

// loginByName
const loginByUsernameRuleFormRef = ref<FormInstance>()
const loginByUsernameForm = ref({username: '', password: ''})

const loginByUsernameRules = ref<FormRules<typeof loginByUsernameForm>>({
  username: [{validator: validateNotNull, trigger: 'change'}],
  password: [{validator: validateNotNull, trigger: 'change'}],
})

const submitLoginByUsername = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(valid => {
    if (valid) {
      console.log('submit!')

      axios.get(`${ServerHost}/loginByUsername?username=${loginByUsernameForm.value.username}&password=${loginByUsernameForm.value.password}`)
          .then(res => {
            if (res.status === 200) {
              console.log(res.data.result)
              switch (res.data.result) {
                case 'usernameNotFound':
                  ElNotification({
                    title: '用户名不存在',
                    type: 'error',
                    position: 'bottom-right',
                  })
                  return
                case 'passwordError':
                  ElNotification({
                    title: '密码错误',
                    type: 'error',
                    position: 'bottom-right',
                  })
                  return
                case 'ok'
                :
                  ElNotification({
                    title: '登录成功',
                    type: 'success',
                    position: 'bottom-right',
                  })
                  localStorage.setItem('loginUser', JSON.stringify(res.data.user))
                  loginUser.value = JSON.parse(localStorage.getItem('loginUser'))
                  accountDialogVisible.value = false
                  return
              }
            } else {
              ElNotification({
                title: '网络异常，请重试',
                type: 'error',
                position: 'bottom-right',
              })
            }
          })
    } else {
      console.log('notSubmit!')

    }
  })
}


// loginByTel
const loginByTelForm = ref({tel: '', code: ''})
const isAbleToGetCode = ref(false)

const validateTel = (rule: any, value: any, callback: any) => {
  console.log(value)
  if (!value) {
    isAbleToGetCode.value = false
    callback(new Error('请输入手机号'))
  }
  if (!/^1[3456789]\d{9}$/.test(value)) {
    isAbleToGetCode.value = false
    callback(new Error('请输入正确的11位手机号'))
  } else {
    isAbleToGetCode.value = true
    callback()
  }
}

const validateCode = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error('请输入验证码'))
    return false
  }
  if (!/^\d{4}$/.test(value)) {
    callback(new Error('请输入4位数字验证码'))
    return false
  } else {
    callback()
    return true
  }
}

const loginByTelRules = ref<FormRules<typeof loginByTelForm>>({
  tel: [{validator: validateTel, trigger: 'change'}],
  code: [{validator: validateCode, trigger: 'change'}],
})

const codeCountdownDefault = 60
const codeCountdown = ref(codeCountdownDefault)
const codeText = ref('获取验证码')
const onGetCode = () => {
  console.log('onGetCode')
  isAbleToGetCode.value = false
  const intervalId = setInterval(() => {
    if (codeCountdown.value > 1) {
      codeCountdown.value--
      codeText.value = codeCountdown.value + 's后可再次获取'
    } else {
      codeCountdown.value = codeCountdownDefault
      codeText.value = '获取验证码'
      isAbleToGetCode.value = true
      clearInterval(intervalId)
    }
  }, 1000);
  axios.get(`${ServerHost}/getTelCode?tel=${loginByTelForm.value.tel}`)
      .then(res => {
        if (res.status === 200 && res.data.result === 'ok') {
          ElNotification({
            title: '验证码已发送，请注意查收',
            message: '[测试]验证码为' + res.data.code,
            type: 'success',
            position: 'bottom-right',
          })
        } else {
          ElNotification({
            title: '验证码发送失败',
            type: 'error',
            position: 'bottom-right',
          })
        }
      })
}

const loginByTelRuleFormRef = ref<FormInstance>()

const submitLoginByTel = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(valid => {
    if (valid) {
      console.log('submit!')
      axios.get(`${ServerHost}/loginByTel?tel=${loginByTelForm.value.tel}&code=${loginByTelForm.value.code}`)
          .then(res => {
            if (res.status === 200) {
              switch (res.data.result) {
                case 'telAndCodeNotFound':
                  ElNotification({
                    title: '验证码错误或超时，请重试',
                    type: 'error',
                    position: 'bottom-right',
                  })
                  return
                case 'newUserRegistered':
                  ElNotification({
                    title: '注册成功',
                    type: 'success',
                    position: 'bottom-right',
                  })
                  localStorage.setItem('loginUser', JSON.stringify(res.data.user))
                  loginUser.value = JSON.parse(localStorage.getItem('loginUser'))
                  accountDialogVisible.value = false
                  return;
                case 'userLogin':
                  ElNotification({
                    title: '登录成功',
                    type: 'success',
                    position: 'bottom-right',
                  })
                  localStorage.setItem('loginUser', JSON.stringify(res.data.user))
                  loginUser.value = JSON.parse(localStorage.getItem('loginUser'))
                  accountDialogVisible.value = false
                  return;
              }

            } else {
              ElNotification({
                title: '登录请求失败，请重试',
                type: 'error',
                position: 'bottom-right',
              })
            }
          })

    } else {
      ElNotification({
        title: '请检查输入信息',
        type: 'warning',
        position: 'bottom-right',
      })
    }
  })
}

// reg
const regForm = ref({username: '', password1: '', password2: ''})

const validateRegPassword1 = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error('请设置密码'))
  } else if (value.length < 6) {
    callback(new Error('密码长度至少为6位'))
  } else {
    callback()
  }
}

const validateRegPassword2 = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error('请再次输入密码'))
  } else if (value != regForm.value.password1) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const regRules = ref<FormRules<typeof regForm>>({
  username: [{validator: validateNotNull, trigger: 'change'}],
  password1: [{validator: validateRegPassword1, trigger: 'change'}],
  password2: [{validator: validateRegPassword2, trigger: 'change'}],
})

const regRuleFormRef = ref<FormInstance>()
const submitReg = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(valid => {
    if (valid) {
      axios.post(`${ServerHost}/reg?username=${regForm.value.username}&password=${regForm.value.password1}`)
          .then(res => {
            if (res.status === 200) {
              console.log(res.data.result)
              switch (res.data.result) {
                case 'usernameExist':
                  ElNotification({
                    title: '用户名已存在，请更换后重试',
                    type: 'error',
                    position: 'bottom-right',
                  })
                  return
                case 'ok':
                  ElNotification({
                    title: '注册成功',
                    type: 'success',
                    position: 'bottom-right',
                  })
                  localStorage.setItem('loginUser', JSON.stringify(res.data.user))
                  loginUser.value = JSON.parse(localStorage.getItem('loginUser'))
                  accountDialogVisible.value = false
                  return
              }
            } else {
              ElNotification({
                title: '网络异常，请重试',
                type: 'error',
                position: 'bottom-right',
              })
            }
          })


    } else {
      ElNotification({
        title: '请检查输入信息',
        type: 'warning',
        position: 'bottom-right',
      })
    }
  })
}

const onClickAccount = () => {
  // 已登录
  if (loginUser.value) {
// 未登录
  } else {
    accountDialogVisible.value = true
  }
}

const onExitAccount = () => {
  loginUser.value = {}
  localStorage.removeItem('loginUser')
  loginUser.value = JSON.parse(localStorage.getItem('loginUser'))
  ElNotification({
    title: '已退出账号',
    type: 'success',
    position: 'bottom-right',
  })
}

</script>

<template>
  <el-menu class="menu justify-center" mode="horizontal">

    <el-menu-item index="0">
      <RouterLink class="flex" to="/">
        <el-image class="w-6 mr-1" :src="mainIcon"/>
        <p>乡兴助农</p>
      </RouterLink>
    </el-menu-item>

    <el-menu-item index="1">
      <RouterLink to="/policy">扶贫政策</RouterLink>
    </el-menu-item>

    <el-menu-item index="2">
      <RouterLink to="/consult">助农咨询</RouterLink>
    </el-menu-item>

    <el-menu-item index="3">
      <RouterLink to="/agritainment">农 家 乐</RouterLink>
    </el-menu-item>

    <el-sub-menu index="4">
      <template #title class="">农 产 品</template>
      <el-menu-item index="4-1">
        <RouterLink to="/shop">进入商城</RouterLink>
      </el-menu-item>
      <el-menu-item index="4-2">
        <RouterLink to="/my-order">我的订单</RouterLink>
      </el-menu-item>
      <el-menu-item index="4-3">
        <RouterLink to="/seller-center">商家中心</RouterLink>
      </el-menu-item>
    </el-sub-menu>

    <el-sub-menu index="5" v-if="loginUser != null" @click="onClickAccount">
      <template #title class="">
        <el-tag>{{ loginUser.username }}</el-tag>
      </template>
      <el-menu-item index="5-1" @click="onExitAccount">退出账号</el-menu-item>
      <el-menu-item index="5-2" @click="accountDialogVisible = true">切换账号</el-menu-item>
      <el-menu-item index="5-3">
        <RouterLink to="/my-account"> 我的账号</RouterLink>
      </el-menu-item>
    </el-sub-menu>

    <el-menu-item index="6" v-else @click="onClickAccount">
      <el-tag size="large">登 录</el-tag>
    </el-menu-item>

  </el-menu>

  <!-- Account Dialog -->
  <el-dialog
      v-model="accountDialogVisible"
      title="使用“乡兴助农”账号">
    <el-tabs class="" v-model="accountTabActiveName">
      <!--   loginByUsername   -->
      <el-tab-pane label="用户名登录" name="loginByUsername">
        <el-form ref="loginByUsernameRuleFormRef" :rules="loginByUsernameRules" label-width="auto"
                 :model="loginByUsernameForm">
          <el-form-item label="用户名" prop="username">
            <el-input placeholder="请输入用户名" v-model="loginByUsernameForm.username" type="text"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input placeholder="请输入密码" v-model="loginByUsernameForm.password" type="password"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitLoginByUsername(loginByUsernameRuleFormRef)">立即登录</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <!--   loginByTel   -->
      <el-tab-pane label="手机号登录" name="loginByTel">
        <el-form ref="loginByTelRuleFormRef" :rules="loginByTelRules" label-width="auto" :model="loginByTelForm">
          <el-form-item label="手机号" prop="tel">
            <el-input placeholder="请输入手机号" v-model="loginByTelForm.tel" type="text"></el-input>
          </el-form-item>
          <el-form-item label="验证码" prop="code">
            <el-input placeholder="请输入验证码" v-model.number="loginByTelForm.code" type="number">
              <template #append>
                <el-button :disabled="!isAbleToGetCode" @click="onGetCode">{{ codeText }}</el-button>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-tag>未注册的手机号将自动注册</el-tag>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitLoginByTel(loginByTelRuleFormRef)">立即登录</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>

<!--      <el-tab-pane label="用微信登录" name="loginByWechat">-->
<!--        开发中-->
<!--      </el-tab-pane>-->
      <!--   Reg   -->
      <el-tab-pane label="注册" name="reg">
        <el-form ref="regRuleFormRef" :rules="regRules" label-width="auto" :model="regForm">
          <el-form-item label="用户名" prop="username">
            <el-input placeholder="请输入用户名" v-model="regForm.username" type="text"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password1">
            <el-input placeholder="请输入密码" v-model="regForm.password1" type="password"></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="password2">
            <el-input placeholder="请输入密码" v-model="regForm.password2" type="password"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitReg(regRuleFormRef)">立即注册</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>
  </el-dialog>
</template>

<style scoped lang="scss">
.menu {
  font-family: "思源宋体 Heavy", serif;
}
</style>
